<template>
<view>
<view class="bg" :style="'opacity:' + 1">
  <image class="bg-image" mode="scaleToFill"></image>
</view>
<view class="top-screen layout-box">
  <view class="select b-arrow" v-if="init_air_grade == 0">
    <picker @change="bindPickerChange" :value="air_grade" :range="select_grade_dict">
      <view class="picker">
        {{select_grade_dict[air_grade]||'全部'}}
      </view>
    </picker>
  </view>
  <view class="select b-arrow" v-else>
    <view class="picker">
      {{select_grade_dict[air_grade]}}
    </view>
  </view>
  <input @blur="getInputValue" :value="air_name" class="search flex-item" placeholder="请输入设备名称">
  
</view>
<view class="stat-bar layout-box" v-if="stat">
    <span>总计: {{stat.total}}</span>
    <span>在线: {{stat.online}}</span>
    <span>开启: {{stat.working}}</span>
    <span class="tips">(数据延迟3～5分钟)</span>
</view>

<view class="control-list clearfix">
  <block v-for="(item, index) in airlist" :key="index">
    <view v-if="online[item.online] == '离线'" class="control-item off">
      <view class="control-box">
        <view class="cont">
          <view class="clearfix">
            <view class="brand">{{airBrand[item.air_brand]}}</view>
            <view class="online">{{online[item.online]}}</view>
          </view>
          <view class="parameter clearfix">
            <view class="name">{{item.air_name}}</view>
            <view class="local">{{item.air_local}}</view>
          </view>
        </view>
        <view class="tit" v-if="item.air_grade">{{grade_dict[item.air_grade]}}年级{{item.air_class}}</view>
        <view class="tit" v-else>{{item.air_class}}</view>
      </view>
    </view>

    <view v-if="online[item.online] == '在线'" :class="'control-item ' + (item.last_adc > item.air_dieline ? 'on' : 'onoff')" :data-id="item.air_id" :data-token="item.air_api_url" :data-state="item.online" :data-brand="item.air_brand" :data-dieline="item.air_dieline" :data-grade="item.air_grade" :data-class="item.air_class" @tap="detailControl">
      <view class="control-box">
        <view class="cont">
          <view class="clearfix">
            <view class="brand">{{airBrand[item.air_brand]}}</view>
            <view class="online">{{item.last_adc > item.air_dieline ? '开' : '关'}}</view>
          </view>
          <view class="parameter clearfix">
            <view class="name">{{item.air_name}}</view>
            <view class="local">{{item.air_local}}</view>
          </view>

        </view>
        <view class="tit" v-if="item.air_grade">{{grade_dict[item.air_grade]}}年级{{item.air_class}}</view>
        <view class="tit" v-else>{{item.air_class}}</view>
      </view>
    </view>
  </block>
  <view class="on-data" v-if="airlist == '' || airlist.length == 0">
    <view class="iconfont icon-no-data"></view>
    <view class="no-text">暂无数据</view>
  </view>
</view>

<view class="loadmore" v-if="isLoading">{{isPullUpText}}</view>

<view class="foot-btn clearfix">
  <view class="btn btn-on" @tap="openAll">打开全部空调</view>
  <view class="btn btn-off" @tap="closeAll">关闭全部空调</view>
</view>
</view>
</template>

<script>
var app = getApp();
var maxHttps = 0;
var dologin = null;

export default {
  data() {
    return {
      air_name: '',
      air_class: uni.getStorageSync("userClass"),
      air_grade: uni.getStorageSync("userGrade"),
      init_air_grade: uni.getStorageSync("userGrade"),
      grade_dict: ['', '一', '二', '三', '四', '五', '六'],
      select_grade_dict: ['全部', '一年级', '二年级', '三年级', '四年级', '五年级', '六年级'],
      operate_user_id: '',
      room_type: '',
      airBrand: {
        1000:"老格力”,
		2000:"大金",
        3000:"AUX",
        4000:"格力",
		5000:"海信",
		6000:"关灯",
		7000:"延时关灯",
      },
      online: ["离线", "在线"],
      pagesize: 10,
      page: 1,
      airlist: [],
      isPullDown: false,
      isPullUp: false,
      isLoading: false,
      isPullUpText: '',
      stat: false,
    };
  },

  components: {},
  props: {},
  onLoad: function (options) {
    var that = this;

    if (uni.getStorageSync("userId") != "") {
      console.log(123);
      that.setData({
        page: 1,
        airlist: [],
        isPullDown: false,
        isPullUp: false,
        isLoading: false,
        isPullUpText: ''
      });
      that.getList();
      dologin = false;
    } else {
      app.globalData.doLogin();
      dologin = true;
    }
  },
  onShow: function () {
    var that = this;

    if (uni.getStorageSync("userId") != "" && dologin === true) {
      console.log(213);
      dologin = false;
      that.setData({
        page: 1,
        airlist: [],
        isPullDown: false,
        isPullUp: false,
        isLoading: false,
        isPullUpText: ''
      });
      that.getList();
    }
  },
  onPullDownRefresh: function () {
    var that = this;

    if (that.isPullUp || that.isPullDown) {
      return;
    }

    that.setData({
      page: 1,
      airlist: [],
      isPullDown: true,
      isPullUp: false,
      isLoading: false,
      isPullUpText: ''
    });
    that.getList();
    uni.stopPullDownRefresh();
  },
  onReachBottom: function () {
    var that = this;

    if (that.isPullUp || that.isPullDown) {
      return;
    }

    that.setData({
      isPullUp: false,
      isPullDown: true,
      isLoading: true
    });
    that.getList();
  },
  methods: {
    getInputValue(e) {
      uni.setStorageSync("search_air_name", e.detail.value);
      this.getList(e.detail.value, uni.getStorageSync("search_air_grade"), 1);
      this.setData({
        air_name: e.detail.value,
        page: 1,
        airlist: []
      });
    },

    bindPickerChange: function (e) {
      this.getList(uni.getStorageSync("search_air_name"), e.detail.value, 1);
      uni.setStorageSync("search_air_grade", e.detail.value); //console.log('picker发送选择改变，携带值为', e.detail.value)

      this.setData({
        air_grade: e.detail.value,
        page: 1,
        airlist: []
      });
    },
    getList: function (air_name = '', air_grade = '', page = '') {
      var that = this;

      if (uni.getStorageSync("userRoleId") == 6 || uni.getStorageSync("userRoleId") == 7) {
        that.setData({
          room_type: 2
        });
      } else if (uni.getStorageSync("userRoleId") == 5) {
        that.setData({
          room_type: 1
        });
      } else {
        that.setData({
          room_type: 0
        });
      }

      let schoolId = uni.getStorageSync('schoolid');
      var jsonData = {
        school_id: schoolId,
        air_name: air_name || '',
        air_class: that.air_class,
        air_grade: air_grade || that.air_grade,
        operate_user_id: uni.getStorageSync("userId"),
        room_type: that.room_type,
        pagesize: that.pagesize,
        page: page || that.page
      };
      app.globalData.JsonPost("api/Air/airList", jsonData, function (res) {
        var airdata = res.data.rows;
        var stat = res.data.stat;
        console.log(stat);

        if (airdata.length > 0) {
          var l = that.airlist;

          for (var i = 0; i < airdata.length; i++) {
            l.push(airdata[i]);
          }

          that.setData({
            airlist: l,
            page: that.page + 1,
            isPullUp: false,
            isPullDown: false,
            isPullUpText: '上拉加载更多',
            stat: stat
          });
        } else {
          that.setData({
            isPullUp: false,
            isPullDown: false,
            isPullUpText: ''
          });
        }
      });
    },
    detailControl: function (e) {
      console.log(e);
      uni.navigateTo({
        url: `detail?air_id=${e.currentTarget.dataset.id}&is_online=${e.currentTarget.dataset.state}&token=${e.currentTarget.dataset.token}&dieline=${e.currentTarget.dataset.dieline}&brand=${e.currentTarget.dataset.brand}&grade=${e.currentTarget.dataset.grade}&class=${e.currentTarget.dataset.class}`
      });
    },
    getAllList: function (cb) {
      var that = this;

      if (uni.getStorageSync("userRoleId") == 6 || uni.getStorageSync("userRoleId") == 7) {
        that.setData({
          room_type: 2
        });
      } else if (uni.getStorageSync("userRoleId") == 5) {
        that.setData({
          room_type: 1
        });
      } else {
        that.setData({
          room_type: 0
        });
      }

      var jsonData = {
        school_id: schoolId,
        air_name: that.air_name,
        air_class: that.air_class,
        air_grade: that.air_grade,
        operate_user_id: uni.getStorageSync("userId"),
        room_type: that.room_type,
        pagesize: 10000,
        page: 1
      };
      app.globalData.JsonPost("api/Air/airList", jsonData, function (res) {
        cb(res.data.rows);
      });
    },
    closeAll: function () {
      var that = this;
      maxHttps = 0;
      that.getAllList(function (data) {
        //在此处开启loading  空调关闭中...请稍后...
        app.globalData.showLoading("关闭中...");

        for (var i in data) {
          var item = data[i];

          if (item.air_api_url != '' && item.online == 1) {
            maxHttps++;
            that.closeAir(item.air_api_url, item.air_brand);
          }

          if (maxHttps == 0) {
            //关闭loading 并告知 空调均已离线,无法操作
            app.globalData.closeLoading();
            uni.showToast({
              title: '空调均已离线,无法操作',
              //设置标题
              duration: 2000,
              //设置显示时间
              mask: true,
              //是否打开遮罩,默认不打开
              icon: 'none' //图标样式，none为无图标

            });
          }
        }
      });
    },
    openAll: function () {
      var that = this;
      maxHttps = 0;
      that.getAllList(function (data) {
        //在此处开启loading  空调开启中...请稍后...
        app.globalData.showLoading("开启中...");

        for (var i in data) {
          var item = data[i];

          if (item.air_api_url != '' && item.online == 1) {
            maxHttps++;
            that.openAir(item.air_api_url, item.air_brand);
          }
        }

        if (maxHttps == 0) {
          //关闭loading 并告知 空调均已离线,无法操作
          uni.showToast({
            title: '空调均已离线,无法操作',
            //设置标题
            duration: 2000,
            //设置显示时间
            mask: true,
            //是否打开遮罩,默认不打开
            icon: 'none' //图标样式，none为无图标

          });
        }
      });
    },
    closeAir: function (token, brand) {
      app.globalData.JsonPost("api/device/rpc", {
        token: token,
        brand: brand,
        code: '00',
        school_id: schoolId
      }, function (res) {
        maxHttps--;

        if (maxHttps == 0) {
          //关闭loading 并提示所有在线空调都已经关闭
          app.globalData.closeLoading();
          uni.showToast({
            title: '在线空调都已经关闭',
            //设置标题
            duration: 2000,
            //设置显示时间
            mask: true,
            //是否打开遮罩,默认不打开
            icon: 'none' //图标样式，none为无图标

          });
        }

        console.log(res);
      });
    },
    openAir: function (token, brand) {
      app.globalData.JsonPost("api/device/rpc", {
        token: token,
        brand: brand,
        school_id: schoolId
      }, function (res) {
        maxHttps--;

        if (maxHttps == 0) {
          //关闭loading 并提示所有在线空调都已经开启
          app.globalData.closeLoading();
          uni.showToast({
            title: '所有在线空调都已经开启',
            //设置标题
            duration: 2000,
            //设置显示时间
            mask: true,
            //是否打开遮罩,默认不打开
            icon: 'none' //图标样式，none为无图标

          });
        }

        console.log(res);
      });
    }
  }
};
</script>
<style>
page {
  padding-top: 40px;
  padding-bottom: 45px;
}

.bg {
  position: fixed;
  top: 0;/*  #ifdef  H5  */
  top: calc(88rpx + constant(safe-area-inset-top));
  top: calc(88rpx + env(safe-area-inset-top));/*  #endif  */
  left: 0;
  width: 100%;
  height: 100%;
  background: url("https://anruisheng.airuis.xyz/public/img/list-bg2.jpg") no-repeat #000;
  background-size: cover;
  z-index: -1;
  border: 0;
  padding: 0;
  margin: 0;
}

.bg-img {
  width: 100%;
  height: 100%;
}

.control-list {
  margin: 6px;
  margin-top: 40px;
}

.control-item {
  float: left;
  width: 50%;
  margin: 3px 0;
}

.control-box {
  padding: 5px;
}

.control-item .cont {
  padding: 10px 6px;
  border-radius: 5px;
}

.control-item.on .cont {
  color: #fff;
  background-color: rgb(41, 140, 235);
}

.control-item.onoff .cont {
  color: #fff;
  background-color: rgb(112,128,144);
}

.control-item.off .cont {
  color: #fff;
  background-color: #9a9a9a;
}

.control-item .brand {
  float: left;
  font-size: 14px;
  line-height: 14px;
  
  padding: 0 5px;
  margin-top: 2px;
}

.control-item .online {
  float: right;
  font-size: 14px;
  line-height: 20px;
}

.control-item .parameter {
  height: 20px;
  font-size: 14px;
  line-height: 20px;
  margin-top: 20px;
}

.control-item .name {
  float: left;
  border-radius: 5px;
  border: 1px solid #fff;
  padding: 0 5px;
}

.control-item .local {
  float: right;
}

.control-item .tit {
  font-size: 12px;
  text-align: center;
  line-height: 18px;
  padding: 4px;
  color: #fff;
  font-weight: 700;
}

/* 下拉提示 */

.loadmore {
  color: #fff;
}

/* 底部按钮 */

.foot-btn~.post-form {
  padding-bottom: 45px;
}

.foot-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 45px;
  background-color: #fff;
  z-index: 10;
}

.foot-btn .btn {
  float: left;
  width: 50%;
  height: 45px;
  color: #fff;
  font-size: 16px;
  line-height: 45px;
  text-align: center;
}

.btn-on {
  background-color: rgb(8, 187, 7);
}

.btn-off {
  background-color: rgb(255, 137, 0);
}

/* 筛选 */

.top-screen {
  position: fixed;
  top: 0;/*  #ifdef  H5  */
  top: calc(88rpx + constant(safe-area-inset-top));
  top: calc(88rpx + env(safe-area-inset-top));/*  #endif  */
  left: 0;
  right: 0;
  width: 100%;
  height: 40px;
  padding: 5px 6px;
  background-color: #fff;
  z-index: 10;
  box-sizing: border-box;
}

.top-screen .search {
  position: relative;
  height: 30px;
  color: #7e7e7e;
  font-size: 14px;
  line-height: 20px;
  background-color: #f8f8f8;
  padding: 5px 9px;
  border-radius: 3px;
  margin-left: 5px;
  box-sizing: border-box;
}

.top-screen .search::after {
  content: "\e64c";
  position: absolute;
  top: 5px;
  right: 10px;
  width: 20px;
  height: 20px;
  font-family: "iconfont" !important;
  color: #bcc0c7;
  font-size: 16px;
  text-align: center;
  line-height: 20px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.top-screen .select {
  width: 80px;
  height: 30px;
  color: #7e7e7e;
  font-size: 14px;
  line-height: 20px;
  padding: 5px 15px 5px 9px;
  background-color: #f8f8f8;
  border-radius: 3px;
  box-sizing: border-box;
}

.top-screen .select.b-arrow:before {
  height: 12rpx;
  width: 12rpx;
  border-width: 1rpx 1rpx 0 0;
  border-color: #bcc0c7;
  right: 8px;
  margin-top: -9rpx;
}

/* 暂无数据 */

.on-data .iconfont {
  color: #fff;
}

.on-data .no-text {
  color: #fff;
}
.stat-bar {
  font-size: 14px;
  font-weight: 300;
  background-color: white;
  text-align: center;
  width: 100%;
  position: fixed;
  top: 80rpx;
  z-index: 10;
  box-sizing: border-box;
  display: inline-block;
  border-top: gainsboro solid 1px;
  padding: 5px;
}
.stat-bar span{margin-right: 10px;}
.stat-bar span.tips {font-size: 12px;}

</style>